<template>
  <a-button class="editable-add-btn" style="margin-bottom: 8px" @click="handleAdd">+</a-button>
  <DynamicTable
    size="small"
    bordered
    :columns="tableColumns"
    editable-type="multiple"
    row-key="id"
    :search="false"
    :show-tool-bar="false"
    :pagination="false"
    :data-source="dataSource"
  >
  </DynamicTable>
</template>
<script lang="tsx" setup>
  import { computed, onMounted, ref } from 'vue';

  import type { Ref } from 'vue';
  import { useTable } from '@/components/core/dynamic-table';
  import { baseColumns } from '@/views/model/manage/detail//monitoringAttribute/columns';

  defineOptions({
    name: 'equipmentParametersForm',
  });

  const [DynamicTable, dynamicTableRef] = useTable();

  const dataSource: Ref<API.CreateAttributeParams[]> = ref([]);

  const tableColumns = computed<typeof baseColumns>(() => [
    ...baseColumns,
    {
      title: '操作',
      align: 'center',
      width: 200,
      dataIndex: 'ACTION',
      actions: ({ record }) => {
        return [
          {
            label: '删除',
            onClick: () => {
              delEditable(record.id);
            },
          },
        ];
      },
    },
  ]);

  const count = computed(() => dataSource.value.length + 1);

  const handleAdd = () => {
    const newData = {
      id: `${count.value}`,
      attributeType: '2',
      name: '',
      numericType: '',
      maximum: '',
      precision: '',
      unit: '',
      remark: '',
    };
    dataSource.value.push(newData);
    dynamicTableRef.startEditable(newData.id, newData);
  };
  const delEditable = (id: String) => {
    const index = dataSource.value.findIndex((obj) => obj.id === id);
    // 如果找到了该对象，则从数组中删除它
    if (index !== -1) {
      dataSource.value.splice(index, 1);
    }
    dynamicTableRef?.reload();
  };
  const valiterData = async () => {
    const result = await Promise.all(
      dataSource.value.map(async (obj) => {
        return await dynamicTableRef.getEditFormModel(obj.id);
      }),
    );
    return result;
  };

  onMounted(() => {
    handleAdd();
  });

  defineExpose({
    valiterData,
    dataSource,
  });
</script>
